package com.epfresh.supplier.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;

import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.http.RequestManager;
import com.epfresh.api.utils.CustomDialog;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.widget.list.LoadMoreListView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.supplier.R;
import com.epfresh.supplier.adapter.PromotionListAdapter;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.entity.Promotion;
import com.epfresh.supplier.entity.PromotionCondition;
import com.epfresh.supplier.entity.TagPager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;


public class ProductPromotionListActivity extends BaseActivity implements LoadMoreListView.IXListViewListener {
//    protected View mainView;
//    protected View vException;
//    protected TextView tvExceptionDescription;
//    protected ImageView ivExceptionIcon;
//    private ProgressBar pb;

    List<Promotion> list = new ArrayList<>();
    private LoadMoreListView mListView;
    private PromotionListAdapter adapter;
    String productId;
    String type;
    String chargeUnit;
    double incr;
    String moq;

    String price,inventory;
    private int PAGE_SIZE = 10;

    boolean isNeedRefresh;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState != null) {
            getIntent().putExtra("productId", savedInstanceState.getString("productId"));
            getIntent().putExtra("type", savedInstanceState.getString("type"));
            getIntent().putExtra("chargeUnit",savedInstanceState.getString("chargeUnit"));
            getIntent().putExtra("inventory",savedInstanceState.getString("inventory"));
            getIntent().putExtra("moq",savedInstanceState.getString("moq"));
            getIntent().putExtra("productStatus",savedInstanceState.getString("productStatus"));
            getIntent().putExtra("incr",savedInstanceState.getDouble("incr"));
            getIntent().putExtra("price",savedInstanceState.getDouble("price"));

        }
        setContentView(R.layout.activity_promotion_list);


        ivBack.setVisibility(View.VISIBLE);
        tvBack.setVisibility(View.VISIBLE);


        productId = getIntent().getStringExtra("productId");
        type = getIntent().getStringExtra("type");
        chargeUnit = getIntent().getStringExtra("chargeUnit");
        moq = getIntent().getStringExtra("moq");
        incr = getIntent().getDoubleExtra("incr",1d);

        price = getIntent().getStringExtra("price");
        inventory = getIntent().getStringExtra("inventory");


        if ("1".equals(type)) {
            toolbarTitle.setText("促销明细");
            rightbtn.setText("添加");
            rightbtn.setVisibility(View.VISIBLE);
        }else {
            toolbarTitle.setText("秒杀明细");
        }
        if (productId == null || "".equals(productId)) {
            finish();
        }
        //初始化view
        initView();
        //加载数据
        refresh();

    }

    private PtrFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, mListView, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    private void refresh() {
        requestTagList(productId, type, 0, PAGE_SIZE);
    }

    private void initHeadView() {
        ptrFrameLayout = (PtrFrameLayout) findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
//        ptrFrameLayout.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                ptrFrameLayout.autoRefresh(true);
//            }
//        }, 200);
    }

    public void initException() {
//        tvExceptionDescription = (TextView) vException.findViewById(R.id.tv_exception);
//        ivExceptionIcon = (ImageView) vException.findViewById(R.id.iv_exception);
//        pb = (ProgressBar) vException.findViewById(R.id.pb);
//        tvExceptionDescription.setOnClickListener(this);
//        ivExceptionIcon.setOnClickListener(this);
    }

    private void initView() {

        initHeadView();
//        vException = findViewById(R.id.v_exception);
//        mainView = findViewById(R.id.fragment_ptr_home_ptr_frame);
        initException();
        mListView = (LoadMoreListView) findViewById(R.id.listview);
        mListView.setXListViewListener(this);
        View vHead = new View(this);
        AbsListView.LayoutParams lp = new AbsListView.LayoutParams(0,LocalDisplay.dp2px(8));
        vHead.setLayoutParams(lp);
        mListView.addHeaderView(vHead);
        adapter = new PromotionListAdapter(this, list, mListView);
        mListView.setAdapter(adapter);
        adapter.setOnNotifyDataSetChangedListener(new PromotionListAdapter.OnNotifyDataSetChangedListener() {
            @Override
            public void OnNotifyDataSetChangedListener(int size) {
                if (size == 0) {
                    requestSucceedCount = 0;
                    showExceptionView(R.mipmap.product_no, "暂无商品，请添加", 1);
                } else {
                    showMainView();
                }
            }
        });

        adapter.setOnChildClickListener(new PromotionListAdapter.OnChildClickListener() {
            @Override
            public void onChildClickListener(int position, int childPosition, Promotion promotion, int type) {
                if (promotion != null ) {
                    if (type == 1) {//编辑

                        String type1 = promotion.getType();

                        if (promotion.isOverStatus()){
                            return;
                        }

                        //1促销2秒杀
                        if ("1".equals(type1)) {
                            intoPromotion(promotion);
                        } else if ("2".equals(type1)) {
                            intoSecKill(promotion);
                        }
                    } else if (type == 0) {//结束活动
                        openStopDialog(promotion.getId());
                    }
                }
            }
        });
    }

    private void intoPromotion(Promotion promotion) {
        Intent intent = new Intent(this, ProductPromotionActivity.class);
//        intent.putExtra("chargeUnit", promotion.getChargeUnit());
//        intent.putExtra("incr", productAddEntity.getIncr());
//        intent.putExtra("moq", productAddEntity.getMoq());
        intent.putExtra("chargeUnit", chargeUnit);
        intent.putExtra("incr", incr);
        intent.putExtra("moq", moq);
        intent.putExtra("productId", productId);
        intent.putExtra("inventory", getIntent().getStringExtra("inventory"));
        if (promotion != null) {
            intent.putExtra("price", promotion.getOriginalCost());
            if (!"0".equals(getIntent().getStringExtra("productStatus")))
            intent.putExtra("promotionStatus", promotion.getPromotionStatus());
            intent.putExtra("promotion", new Gson().toJson(promotion));
        }
//        if (hasProductId()) {
//            intent.putExtra("isEdit", true);
//        }

        startActivityForResult(intent, 0x1947);
    }

    private void intoSecKill(Promotion promotion) {
        Intent intent = new Intent(this, ProductSecKillActivity.class);
        intent.putExtra("chargeUnit", chargeUnit);
        intent.putExtra("incr", incr);
        intent.putExtra("moq", moq);
        intent.putExtra("productId", productId);
        intent.putExtra("inventory", getIntent().getStringExtra("inventory"));
        if (promotion != null) {
            intent.putExtra("price", promotion.getOriginalCost());
            if (!"0".equals(getIntent().getStringExtra("productStatus")))
                intent.putExtra("promotionStatus", promotion.getPromotionStatus());
            intent.putExtra("promotion", new Gson().toJson(promotion));
        }
//        if (hasProductId()) {
//            intent.putExtra("isEdit", true);
//        }

        startActivityForResult(intent, 0x1947);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.ci_start_time:

                break;
            case R.id.ci_end_time:

                break;
            case R.id.tv_btn:

                break;
        }
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {

        outState.putString("productId", getIntent().getStringExtra("productId"));
        outState.putString("type", getIntent().getStringExtra("type"));
        outState.putString("chargeUnit", getIntent().getStringExtra("chargeUnit"));
        outState.putString("inventory", getIntent().getStringExtra("inventory"));

        outState.putString("moq",getIntent().getStringExtra("moq"));
        outState.putDouble("incr",getIntent().getDoubleExtra("incr",0d));
        super.onSaveInstanceState(outState);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0x1947 && resultCode == RESULT_OK) {
            isNeedRefresh = true;
            refresh();
        }
        if (requestCode == 0x1948 && resultCode == RESULT_OK) {//秒杀
            isNeedRefresh = true;
            refresh();
        }
    }

    RequestTag requestTag;

    private void requestTagList(String productId, String type, int pageNumber, int pageSize) {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_promotion_page);
//        "productId":1234
//        "type":1
        RequestEntityMapSupply.putParameter("productSpecId", productId);
        RequestEntityMapSupply.putParameter("type", type);
        RequestEntityMapSupply.putParameter("pageNumber", pageNumber);
        RequestEntityMapSupply.putParameter("pageSize", pageSize);
        if (requestTag == null) {
            requestTag = new RequestTag();
            requestTag.tag = com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_promotion_page;
            requestTag.type = RequestTag.TYPE_CURRENT;
        }


        requestTag.action = pageNumber;
        request(RequestEntityMapSupply, requestTag, onTagListRequestListener);

    }

    private PromotionCondition promotionCondition;
    private OnRequestListener<ContentEntity<Promotion>> onTagListRequestListener = new OnRequestListener<ContentEntity<Promotion>>() {
        @Override
        public ContentEntity<Promotion> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<ContentEntity<Promotion>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
            if (requestSucceedCount == 0) {
                showExceptionView(R.mipmap.icon_error, BaseApplication.getDoc().getNetWeak(), HttpRequest.FAIL_NET_FAULT);
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
           if (requestSucceedCount == 0) {
            showExceptionView(R.mipmap.icon_error, arg + "", HttpRequest.FAIL_NET_FAULT);
        }
        RequestTag requestTag = (RequestTag) tag;
        updateViewStatus(requestTag);
        }

        @Override
        public void onStart(Object tag) {
            if (requestSucceedCount == 0) {
                showProgressView();
            }
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<Promotion>> response, Object tag) {

            if (requestSucceedCount == 0) {
                showMainView();
            }
            requestSucceedCount++;

            ContentEntity<Promotion> responseElement = response.getResponseElement();

            if (responseElement != null) {
                List<Promotion> content = responseElement.getContent();

                if (requestTag.action == 0) {
                    list.clear();
                }
                list.addAll(content);
                adapter.notifyDataSetChanged();
                tagPager.setLast(responseElement.getLast());
                tagPager.setNumber(responseElement.getNumber());
                tagPager.setSize(responseElement.getSize());
                tagPager.setTotalElements(responseElement.getTotalElements());
            }
            updateViewStatus(requestTag);
        }
    };

    @Override
    protected void onDestroy() {
        RequestManager.getInstance().cancel(requestTag);
        super.onDestroy();
    }
    private int requestSucceedCount = 0;
    private TagPager tagPager = new TagPager();
    public void updateViewStatus(RequestTag requestTag) {
        ptrFrameLayout.refreshComplete();
        if (tagPager.isLast()) {
            mListView.noMore();
        } else {
            mListView.stopLoadMore();
        }
    }

    @Override
    public void onLoadMore() {
        int number = tagPager.getNumber();
        requestTagList(productId, type, number + 1, PAGE_SIZE);
    }

    private void requestPromotionStop(String id) {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_promotion_over);
        RequestEntityMapSupply.putParameter("id", id);
        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_promotion_over, onPromotionStopRequestListener);

    }

    private OnRequestListener<StatusEntity> onPromotionStopRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

            hideProgressDialog();
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                refresh();
            } else {

            }

        }
    };


    CustomDialog.Builder builderStop;

    private void openStopDialog(final String id) {
        if (builderStop == null) {
            builderStop = new CustomDialog.Builder(this);

        }
        String s = "是否结束活动";

        builderStop.setTitleVisible(false).setMessage(s)//设置显示的内容
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        requestPromotionStop(id);
                        dialog.dismiss();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
                dialog.dismiss();
            }

        });//在按键响应事件中显示此对话框

        builderStop.create().show();
    }

    @Override
    public void onRightClick() {
        //onBackPressed();
        Intent intent = new Intent(this, ProductPromotionActivity.class);
//        intent.putExtra("chargeUnit", promotion.getChargeUnit());
//        intent.putExtra("incr", productAddEntity.getIncr());
//        intent.putExtra("moq", productAddEntity.getMoq());
        intent.putExtra("chargeUnit", chargeUnit);
        intent.putExtra("incr", incr);
        intent.putExtra("moq", moq);
        intent.putExtra("productId", productId);
        intent.putExtra("inventory", inventory);
        intent.putExtra("price", price);

        startActivityForResult(intent, 0x1948);
    }

    @Override
    public void onBackPressed() {
        if (isNeedRefresh) {
            Intent intent = new Intent();
            intent.putExtra("isNeedRefresh", isNeedRefresh);
            setResult(RESULT_OK,intent);
            finish();
        } else
            super.onBackPressed();
    }
}
